import GlobalManager from "./util/globlaManager";
const configIp = GlobalManager.configIp;

cc.Class({
    extends: cc.Component,

    properties: {
        progressLabel: cc.Label,
        tipLabel: cc.Label,
        progressBar: cc.ProgressBar,
    },

    start() {

    },

    onLoad() {
        this.loadConfig(() => {
            let serverIp = GlobalManager.serverIp;
            let port_hot = GlobalManager.port_hot;
            let isDebug = GlobalManager.isDebug;
            let hall_version = "v" + GlobalManager.hall_version;
            let panel_version = "v" + GlobalManager.panel_version;
            console.log("serverIp:", serverIp);
            console.log("port_hot:", port_hot);
            console.log("isDebug:", isDebug);
            console.log("hall_version:", hall_version);
            console.log("panel_version:", panel_version);
            
            
            if (isDebug) {
                this.loadHallBundleDebug();
            } else {
                this.loadHallBundle(serverIp, port_hot, hall_version, panel_version);
            }
        });
    },

    onClick(event, target) {
        // 这里可以处理点击事件
        switch (target) {
            case 'close_tip':
               this.node.getChildByName('tips').active = false;
                break;
            default:
                break;
        }
    },


    // 加载大厅资源包和面板资源包
    loadHallBundle(serverIp, port_hot, hall_version, panel_version) {

        let self = this;
        self.tipLabel.string = "Loading lobby resources...";
        let bundleUrl = "http://" + serverIp + ":" + port_hot + "/hotUpdate/hall/" + hall_version;

        cc.assetManager.loadBundle(bundleUrl, function (err, hallBundle) {
            if (err) {
                console.error('加载 hall 资源包失败:', err);
                return;
            }

            hallBundle.loadDir('', function (completedCount, totalCount, item) {
                let progress = completedCount / totalCount;
                // console.log(`hall 资源加载进度: ${(progress * 100).toFixed(2)} (${completedCount}/${totalCount})`);
                self.progressLabel.string = (progress * 100).toFixed(2) + "%";
                self.progressBar.progress = progress;
            }, function (err, assets) {
                if (err) {
                    console.error('加载 hall 资源失败:', err);
                    return;
                }
                console.log('✅hall 资源加载完成!');
                self.tipLabel.string = "Loading panel resources...";
                // 加载 panel 资源包
                let panelBundleUrl = "http://" + serverIp + ":" + port_hot + "/hotUpdate/panel/" + panel_version;

                cc.assetManager.loadBundle(panelBundleUrl, function (err, panelBundle) {
                    if (err) {
                        console.error('加载 panel 资源包失败:', err);
                        return;
                    }

                    panelBundle.loadDir('', function (completedCount, totalCount, item) {
                        let progress = completedCount / totalCount;
                        // console.log(`panel 资源加载进度: ${(progress * 100).toFixed(2)} (${completedCount}/${totalCount})`);
                        self.progressLabel.string = (progress * 100).toFixed(2) + "%";
                        self.progressBar.progress = progress;
                    }, function (err, assets) {
                        if (err) {
                            console.error('加载 panel 资源失败:', err);
                            return;
                        }
                        console.log('✅panel 资源加载完成!');

                        // 加载完成后可切换场景或执行其他逻辑
                        cc.director.loadScene("lobbyMain");
                    });
                });
            });
        });
    },

    //调试状态下加载大厅
    loadHallBundleDebug() {
        let self = this;
        self.tipLabel.string = "Loading lobby resources...";

        // 加载本地 hall bundle（不需要加路径前缀）
        cc.assetManager.loadBundle("hall", function (err, hallBundle) {
            if (err) {
                console.error('加载本地 hall 资源包失败:', err);
                return;
            }

            hallBundle.loadDir('', function (completedCount, totalCount, item) {
                let progress = completedCount / totalCount;
                // console.log(`hall 资源加载进度: ${(progress * 100).toFixed(2)} (${completedCount}/${totalCount})`);
                self.progressLabel.string = (progress * 100).toFixed(2) + "%";
                self.progressBar.progress = progress;
            }, function (err, assets) {
                if (err) {
                    console.error('加载 hall 资源失败:', err);
                    return;
                }
                console.log('✅hall 资源加载完成!');
                self.tipLabel.string = "Loading panel resources...";

                // 加载本地 panel bundle
                cc.assetManager.loadBundle("panel", function (err, panelBundle) {
                    if (err) {
                        console.error('加载本地 panel 资源包失败:', err);
                        return;
                    }

                    panelBundle.loadDir('', function (completedCount, totalCount, item) {
                        let progress = completedCount / totalCount;
                        // console.log(`panel 资源加载进度: ${(progress * 100).toFixed(2)} (${completedCount}/${totalCount})`);
                        self.progressLabel.string = (progress * 100).toFixed(2) + "%";
                        self.progressBar.progress = progress;
                    }, function (err, assets) {
                        if (err) {
                            console.error('加载 panel 资源失败:', err);
                            return;
                        }
                        console.log('✅panel 资源加载完成!');

                        // 加载完成后可切换场景或执行其他逻辑
                        cc.director.loadScene("lobbyMain");
                    });
                });
            });
        });
    },


    //加载config
    loadConfig(callback) {
        let timestamp = new Date().getTime(); // 添加时间戳
        let url = `http://${configIp}:81/config/config.json?_=${timestamp}`;
        let headers = {
            'Cache-Control': 'no-cache', // 强制不缓存
            'Pragma': 'no-cache',
            'Expires': '0',
        };

        cc.assetManager.loadRemote(url, { headers }, (err, jsonAsset) => {
            if (err) {
                console.error('加载远程 config.json 失败', err);
                return;
            }
            for (let key in jsonAsset.json) {
                GlobalManager[key] = jsonAsset.json[key];
            }
            if (callback) callback(); // 加载成功后执行回调
        });
    },


    update(dt) {
        // 每帧更新
    },
});
